package com.xyz.livelib.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.ScreenUtils;
import com.xyz.livelib.R;
import com.xyz.livelib.rtmp.OnConntionListener;
import com.xyz.livelib.rtmp.RtmpHelper;
import com.xyz.livelib.rtmp.encoder.BasePushEncoder;
import com.xyz.livelib.rtmp.encoder.PushEncode;

public class RecordScreenService extends Service implements OnConntionListener,
        BasePushEncoder.OnMediaInfoListener {

    private Intent data;
    private int code;
    private String url;
    private MediaProjectionManager projectionManager;
    private MediaProjection mediaProjection;
    private int width;
    private int height;
    private RtmpHelper rtmpHelper;
    private PushEncode pushEncode;

    @Override
    public void onCreate() {
        super.onCreate();
        projectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        width = ScreenUtils.getScreenWidth();
        height = ScreenUtils.getScreenHeight();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        code = intent.getIntExtra("code", -1);
        data = intent.getParcelableExtra("data");
        url = intent.getStringExtra("url");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            createNotificationChannel(); //创建通知栏，你正在录屏
        }
        mediaProjection = projectionManager.getMediaProjection(code, data);
        if (mediaProjection == null) {
            Log.e("@@", "media projection is null");
            return Service.START_STICKY;
        }
        rtmpHelper = new RtmpHelper();
        rtmpHelper.setOnConntionListener(this);
        rtmpHelper.initLivePush(url);
        return Service.START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void createNotificationChannel() {
        Notification.Builder builder = new Notification.Builder(this.getApplicationContext()); //获取一个Notification构造器
        Intent nfIntent = new Intent(this, RecordScreenService.class); //点击后跳转的界面，可以设置跳转数据

        builder.setContentIntent(PendingIntent.getActivity(this, 0, nfIntent, 0)) // 设置PendingIntent
                //.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.mipmap.logo)) // 设置下拉列表中的图标(大图标)
                //.setContentTitle("SMI InstantView") // 设置下拉列表里的标题
                .setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏内的小图标
                .setContentText("正在直播...") // 设置上下文内容
                .setWhen(System.currentTimeMillis()); // 设置该通知发生的时间

        /*以下是对Android 8.0的适配*/
        //普通notification适配
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder.setChannelId("notification_id");
        }
        //前台服务notification适配
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            NotificationChannel channel = new NotificationChannel("notification_id", "notification_name", NotificationManager.IMPORTANCE_LOW);
            notificationManager.createNotificationChannel(channel);
        }

        Notification notification = builder.build(); // 获取构建好的Notification
        notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
        startForeground(110, notification);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        release();
    }

    @Override
    public void onConntecting() {
        Log.e("chenzhu", "连接中...");
    }

    @Override
    public void onConntectSuccess() {
        Log.e("chenzhu", "onConntectSuccess...");
        startPush();
    }

    @Override
    public void onConntectFail(String msg) {
        Log.e("chenzhu", "onConntectFail  $msg");
        release();
    }

    private void startPush() {
        if (mediaProjection == null) return;
        pushEncode = new PushEncode(this);
        pushEncode.initEncoder(
                true, mediaProjection, width, height, 44100, 2, 16
        );
        pushEncode.setOnMediaInfoListener(this);
        pushEncode.start();
    }

    @Override
    public void onMediaTime(int times) {
        Log.e("chenzhu", "onMediaTime  $times");
    }

    @Override
    public void onSPSPPSInfo(byte[] sps, byte[] pps) {
        if (rtmpHelper == null) return;
        rtmpHelper.pushSPSPPS(sps, pps);
    }

    @Override
    public void onVideoDataInfo(byte[] data, boolean keyFrame) {
        if (rtmpHelper == null) return;
        rtmpHelper.pushVideoData(data, keyFrame);
    }

    @Override
    public void onAudioInfo(byte[] data) {
        if (rtmpHelper == null) return;
        rtmpHelper.pushAudioData(data);
    }

    private void release() {
        if (pushEncode != null) {
            pushEncode.stop();
            pushEncode = null;
        }
        if (rtmpHelper != null) {
            rtmpHelper.stop();
            rtmpHelper = null;
        }
    }
}
